package com.lsl.rdf.config;

import com.lsl.rdf.interceptor.UserAuthenticationInterceptor;
import com.lsl.rdf.service.UserSupport;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Arrays;
import java.util.List;

/**
 * Created by lsl on 2021/4/16.
 */
@Slf4j
@Component
// 注解方式启用
@ConditionalOnWebApplication
// 配置文件方式启用
@ConditionalOnProperty(prefix = "rdf.user", name = "enableAuth", havingValue = "true", matchIfMissing = true)
public class WebMvcConfig implements WebMvcConfigurer {

    private final UserSupport userSupport;
    private final UserProperties userProperties;

    /**
     * 默认忽略拦截url
     */
    private static final List<String> excludePathPatterns = Arrays.asList(
            "/doc.html",
            "/actuator/**",
            "/swagger-resources/**",
            "/swagger-ui.html",
            "/*/api-docs",
            "/webjars/**",
            "/user/*/register",
            "/user/*/login",
            "/user/*/refreshToken");

    public WebMvcConfig(UserSupport userSupport, UserProperties userProperties) {
        this.userSupport = userSupport;
        this.userProperties = userProperties;
    }

    @Bean
    private HandlerInterceptor interceptor() {
        return new UserAuthenticationInterceptor(userSupport);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration interceptor = registry.addInterceptor(interceptor());
        log.info("[RDF-COMPONENT-USER] UserAuthenticationInterceptor initialization completed.");

        interceptor
                .addPathPatterns("/**")
                .excludePathPatterns(excludePathPatterns)
                .excludePathPatterns(userProperties.getApiWhitelist());
        log.info("[RDF-COMPONENT-USER] Custom api whitelist: {}", userProperties.getApiWhitelist());
    }
}
